/*
 Copyright (c) 2009 Rafal Szemraj - http://szemraj.eu

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all 
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/
package eu.szemraj.display.ui {
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	import flash.events.MouseEvent;
	import eu.szemraj.display.DisposableSprite;

	/**
	 * @author sema
	 */
	public class Button extends DisposableSprite {
		
		protected static const CONTINUOUS_PRESS_INTERVAL:int = 250;
		protected var _continuousPress:Boolean = true;
		protected var _continuousPressIntervalId:uint;

		public function Button() {
			
			super( );
			enabled = true;	
		}
		
		public function get continuousPress():Boolean {
			return _continuousPress;
		}
		
		public function set continuousPress(value:Boolean):void {
			
			_continuousPress = value;
			if( _continuousPress )
				addEventListener( MouseEvent.MOUSE_DOWN, mouseDownHandler );
			else 
				removeEventListener( MouseEvent.MOUSE_DOWN, mouseDownHandler );
				
		}
		
		public function set enabled( value:Boolean ):void {
			
			useHandCursor = buttonMode = mouseEnabled = value;
			
		}
		
		public function get enabled():Boolean {
			
			return mouseEnabled;
		}
		
		private function mouseDownHandler(event:MouseEvent):void {
			
			if( continuousPress ) {
				
				_continuousPressIntervalId = setInterval( sendPressEvent, CONTINUOUS_PRESS_INTERVAL );
				stage.addEventListener( MouseEvent.MOUSE_UP, mouseUpHandler );
				removeEventListener( MouseEvent.MOUSE_DOWN, mouseDownHandler );
				
			}
		}
		
		private function mouseUpHandler(event:MouseEvent):void {
			
			stage.removeEventListener( event.type, mouseUpHandler );
			if( continuousPress )
				addEventListener( MouseEvent.MOUSE_DOWN, mouseDownHandler );
			clearInterval( _continuousPressIntervalId );
		}

		private function sendPressEvent():void {
			
			dispatchEvent( new MouseEvent( MouseEvent.MOUSE_DOWN  ) );
		}

		
		
		
	}
}
